package com.ewanghuiju.app.util;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.model.http.exception.ApiException;
import com.ewanghuiju.app.model.http.response.MyHttpResponse;
import com.ewanghuiju.app.model.http.response.Optional;
import com.ewanghuiju.app.ui.login.activity.LoginMainActivity;
import com.muddzdev.styleabletoast.StyleableToast;

import org.reactivestreams.Publisher;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author sj  qq:751943509
 * @class describe
 * @time 2020/2/11
 */
public class RxUtil {

    /**
     * 统一线程处理
     *
     * @param <T>
     * @return
     */
    public static <T> FlowableTransformer<T, T> rxSchedulerHelper() {    //compose简化线程
        return new FlowableTransformer<T, T>() {
            @Override
            public Flowable<T> apply(Flowable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * 统一返回结果处理
     * @param <T>
     * @return
     */
//    public static <T> FlowableTransformer<GankHttpResponse<T>, T> handleResult() {   //compose判断结果
//        return new FlowableTransformer<GankHttpResponse<T>, T>() {
//            @Override
//            public Flowable<T> apply(Flowable<GankHttpResponse<T>> httpResponseFlowable) {
//                return httpResponseFlowable.flatMap(new Function<GankHttpResponse<T>, Flowable<T>>() {
//                    @Override
//                    public Flowable<T> apply(GankHttpResponse<T> tGankHttpResponse) {
//                        if(!tGankHttpResponse.getError()) {
//                            return createData(tGankHttpResponse.getResults());
//                        } else {
//                            return Flowable.error(new ApiException("服务器返回error"));
//                        }
//                    }
//                });
//            }
//        };
//    }

    /**
     * 统一返回结果处理
     * @param <T>
     * @return
     */
//    public static <T> FlowableTransformer<WXHttpResponse<T>, T> handleWXResult() {   //compose判断结果
//        return new FlowableTransformer<WXHttpResponse<T>, T>() {
//            @Override
//            public Flowable<T> apply(Flowable<WXHttpResponse<T>> httpResponseFlowable) {
//                return httpResponseFlowable.flatMap(new Function<WXHttpResponse<T>, Flowable<T>>() {
//                    @Override
//                    public Flowable<T> apply(WXHttpResponse<T> tWXHttpResponse) {
//                        if(tWXHttpResponse.getCode() == 200) {
//                            return createData(tWXHttpResponse.getNewslist());
//                        } else {
//                            return Flowable.error(new ApiException(tWXHttpResponse.getMsg(), tWXHttpResponse.getCode()));
//                        }
//                    }
//                });
//            }
//        };
//    }

    /**
     * 统一返回结果处理
     *
     * @param <T>
     * @return
     */
    public static <T> FlowableTransformer<MyHttpResponse<T>, T> handleMyResult() {   //compose判断结果
        return new FlowableTransformer<MyHttpResponse<T>, T>() {
            @Override
            public Publisher<T> apply(Flowable<MyHttpResponse<T>> upstream) {
                try {
                    return upstream.flatMap(new Function<MyHttpResponse<T>, Flowable<T>>() {
                        @Override
                        public Flowable<T> apply(MyHttpResponse<T> tMyHttpResponse) {
                            if (tMyHttpResponse.getCode() == 0) {
//                            LogUtil.i(new GsonBuilder().create().toJson(tMyHttpResponse.getData()));
                                return createData(tMyHttpResponse.getData());
                            } else {
                                if (tMyHttpResponse.getCode() == 403) {
                                    //退出登录  去登录页面
                                    App.getInstance().finishActivity();
                                    Intent intent = new Intent(App.getInstance(), LoginMainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    App.getInstance().startActivity(intent);
                                }
                                return Flowable.error(new ApiException(tMyHttpResponse.getMsg(), tMyHttpResponse.getCode()));
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    return Flowable.error(new ApiException(Constants.ERROR_MESSAGE, Constants.NO_KNOW_EROO));
                }
            }
        };
    }

    public static <T> FlowableTransformer<MyHttpResponse<T>, Optional<T>> handleMyResultCannull() {   //compose判断结果
        return new FlowableTransformer<MyHttpResponse<T>, Optional<T>>() {
            @Override
            public Publisher<Optional<T>> apply(Flowable<MyHttpResponse<T>> upstream) {
                try {
                    return upstream.flatMap(new Function<MyHttpResponse<T>, Flowable<Optional<T>>>() {
                        @Override
                        public Flowable<Optional<T>> apply(MyHttpResponse<T> tMyHttpResponse) {
                            if (tMyHttpResponse.getCode() == 0) {
                                return createDataCannull(tMyHttpResponse.transform());
                            } else {
                                if (tMyHttpResponse.getCode() == 403) {
                                    //退出登录  去登录页面
                                    App.getInstance().finishActivity();
                                    Intent intent = new Intent(App.getInstance(), LoginMainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    App.getInstance().startActivity(intent);
                                }
                                return Flowable.error(new ApiException(tMyHttpResponse.getMsg(), tMyHttpResponse.getCode()));
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    return Flowable.error(new ApiException(Constants.ERROR_MESSAGE, Constants.NO_KNOW_EROO));
                }
            }
        };
    }


    /**
     * 带有后台返回提示的 数据处理
     *
     * @param <T>
     * @return
     */
    public static <T> FlowableTransformer<MyHttpResponse<T>, Optional<T>> handleMyResultCannullWithToast() {
        return new FlowableTransformer<MyHttpResponse<T>, Optional<T>>() {
            @Override
            public Publisher<Optional<T>> apply(Flowable<MyHttpResponse<T>> upstream) {
                try {
                    return upstream.flatMap(new Function<MyHttpResponse<T>, Flowable<Optional<T>>>() {
                        @Override
                        public Flowable<Optional<T>> apply(MyHttpResponse<T> tMyHttpResponse) {
                            if (tMyHttpResponse.getCode() == 0) {
                                StyleableToast.makeText(App.getInstance(), TextUtils.isEmpty(tMyHttpResponse.getMsg()) ? "成功" : tMyHttpResponse.getMsg(), Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return createDataCannull(tMyHttpResponse.transform());
                            } else {
                                if (tMyHttpResponse.getCode() == 403) {
                                    //退出登录  去登录页面
                                    App.getInstance().finishActivity();
                                    Intent intent = new Intent(App.getInstance(), LoginMainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    App.getInstance().startActivity(intent);
                                }
                                return Flowable.error(new ApiException(tMyHttpResponse.getMsg(), tMyHttpResponse.getCode()));
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    return Flowable.error(new ApiException(Constants.ERROR_MESSAGE, Constants.NO_KNOW_EROO));
                }
            }
        };
    }

    /**
     * 生成Flowable
     * 可以生成null
     *
     * @param <T>
     * @return
     */
    public static <T> Flowable<Optional<T>> createDataCannull(Optional<T> t) {
        return Flowable.create(new FlowableOnSubscribe<Optional<T>>() {
            @Override
            public void subscribe(FlowableEmitter<Optional<T>> emitter) throws Exception {
                try {
                    emitter.onNext(t);
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }, BackpressureStrategy.BUFFER);
    }

    public static <T> Flowable<T> createData(final T t) {
        return Flowable.create(new FlowableOnSubscribe<T>() {
            @Override
            public void subscribe(FlowableEmitter<T> emitter) throws Exception {
                try {
                    emitter.onNext(t);
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }, BackpressureStrategy.BUFFER);
    }
}

